import React, { useCallback, useContext, useEffect } from "react";
import update from "immutability-helper";
import { Form, Input, Checkbox, Select } from "antd";
import DndFormCtx from "../core";

const { Item: FormItem } = Form;

const Group = (props: ActivedElemnetType<FunFormGroup>) => {
  const { element, position } = props;
  const { instance, updateInstance } = useContext(DndFormCtx);

  const [form] = Form.useForm<FunFormGroup>();

  useEffect(() => {
    form.setFieldsValue({ ...element });
  }, [element, form]);

  const handleChange = useCallback(() => {
    form.validateFields().then((value: FunFormGroup) => {
      updateInstance(
        update(instance, {
          groups: {
            [position.groupIndex]: {
              $apply(old) {
                return { ...old, ...value };
              },
            },
          },
        })
      );
    });
  }, [instance, position, form, updateInstance]);
  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={{ ...element }}
      onChange={handleChange}
      onFinish={handleChange}
    >
      <FormItem
        label="分区名称"
        required
        name="title"
        rules={[
          {
            required: true,
            message: "请输入分区名称",
          },
        ]}
      >
        <Input></Input>
      </FormItem>
      <FormItem label="分区样式" name="border">
        <Select
          onChange={(v) => {
            form.setFieldsValue({ border: v });
            form.submit();
          }}
        >
          <Select.Option value={1}>无边框</Select.Option>
          <Select.Option value={2}>有边框</Select.Option>
          <Select.Option value={3}>标签页显示</Select.Option>
        </Select>
      </FormItem>
      <FormItem label="是否隐藏" valuePropName="checked" name="isHide">
        <Checkbox
          onChange={({ target: { checked } }) => {
            form.setFieldsValue({ isHide: checked });
            form.submit();
          }}
        ></Checkbox>
      </FormItem>
    </Form>
  );
};

export default Group;
